/**
 * Copyright 2015 ABSir's Studio
 * 
 * All right reserved
 *
 * Create on 2015年7月10日 下午3:22:43
 */
package com.absir.appserv.slave.service;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

import com.absir.appserv.slave.bean.base.JbBeanLTargets;
import com.absir.appserv.system.bean.value.JiActive;
import com.absir.appserv.system.service.ActiveService.ActiveServiceData;
import com.absir.core.kernel.KernelLang.ObjectEntry;

/**
 * @author absir
 *
 */
public abstract class ActiveServiceTargetsSingle<T extends JiActive, K> extends ActiveServiceData<T, ObjectEntry<T, K>> {

	/**
	 * @param active
	 * @return
	 */
	public JbBeanLTargets getBeanLTargets(T active) {
		return (JbBeanLTargets) active;
	}

	/** singleEntry */
	private ObjectEntry<T, K> singleEntry;

	/** singleEntryMap */
	private Map<Long, ObjectEntry<T, K>> singleEntryMap = new HashMap<Long, ObjectEntry<T, K>>();

	/**
	 * @param serverId
	 * @return
	 */
	public ObjectEntry<T, K> getSingleEntry(long serverId) {
		ObjectEntry<T, K> entry = singleEntryMap.get(serverId);
		return entry == null ? singleEntry : entry;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.absir.appserv.system.service.ActiveService#createActiveContext
	 * (com.absir.appserv.system.bean.value.JiActive)
	 */
	@Override
	protected ObjectEntry<T, K> createActiveContext(T active) {

		ObjectEntry<T, K> entry = new ObjectEntry<T, K>(active, createActiveContextSingle(active));
		addObjectEntry(active, entry);
		return entry;
	}

	/**
	 * @param active
	 * @param entry
	 */
	public void addObjectEntry(T active, ObjectEntry<T, K> entry) {
		JbBeanLTargets targets = getBeanLTargets(active);
		if (targets == null || targets.getTargets() == null || targets.getTargets().length == 0) {
			singleEntry = entry;

		} else {
			for (long id : targets.getTargets()) {
				singleEntryMap.put(id, entry);
			}
		}
	}

	protected abstract K createActiveContextSingle(T active);

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.absir.appserv.system.service.ActiveService#updateActiveContext
	 * (com.absir.appserv.system.bean.value.JiActive, java.lang.Object)
	 */
	@Override
	protected ObjectEntry<T, K> updateActiveContext(T active, ObjectEntry<T, K> activeContext) {

		activeContext.setKey(active);
		return activeContext;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.absir.appserv.system.service.ActiveService.ActiveServiceData#
	 * closeActiveContext(java.io.Serializable, java.lang.Object)
	 */
	@Override
	protected void closeActiveContext(Serializable id, ObjectEntry<T, K> activeContext) {

		super.closeActiveContext(id, activeContext);
		singleEntry = null;
		singleEntryMap.clear();
		for (ObjectEntry<T, K> entry : activerMap.getOnlineActiveContexts().values()) {
			addObjectEntry(entry.getKey(), entry);
		}
	}
}
